import { Pie, Column, Line } from '@ant-design/plots';
import { useQuery } from '@tanstack/react-query';
import { Card, App } from 'antd';
import React, { useState } from 'react';
import dayjs from 'dayjs';
import { useApiRequest } from "../../hook/useApiRequest.ts";
import SearchForm, { ISearchFormRef } from "../searchForm/index.tsx";
import useBuildSearchFilters from "../../hook/useBuildSearchFilters.ts";
import { FormItemConfigs, TPageRequest } from "../../global.ts";
import { useQueryClient } from "@tanstack/react-query";

// 图表类型定义
export type ChartType = 'pie' | 'column' | 'line' | 'donut';

// 接口和类型定义
export interface D8dChartsApiConfig {
  search: string;
}

export interface D8dChartsProps {
  type: ChartType;
  title?: string;
  apiConfig: D8dChartsApiConfig;
  xField?: string;
  yField?: string;
  colorField?: string;
  showSearch?: boolean;
  searchFormFieldConfig?: FormItemConfigs[];
  fixedSearchCondition?: any;
  queryKey?: string;
  mountSubmitSearch?: boolean;
  data?: any[];
}

export function D8dCharts({
  type = 'pie',
  title,
  apiConfig,
  xField = 'time_interval',
  yField = 'total_devices',
  colorField = '设备分类',
  showSearch = false,
  searchFormFieldConfig,
  fixedSearchCondition = {},
  queryKey,
  mountSubmitSearch = false,
  data: propsData
}: D8dChartsProps) {
  const { message } = App.useApp();
  const { requestWithToken } = useApiRequest();
  const { buildSearchFilters } = useBuildSearchFilters({ searchFormFieldConfig });
  const searchFormRef = React.useRef<ISearchFormRef>(null);
  const queryClient = useQueryClient();
  const [manualSearchValues, setManualSearchValues] = useState<any>({});

  // 查询函数
  const fetchChartData = async () => {
    if (!apiConfig.search) return [];
    
    const searchValues = mountSubmitSearch 
      ? searchFormRef.current?.getFormValues() 
      : manualSearchValues;
    
    const combinedSearchData = {
      ...fixedSearchCondition,
      ...searchValues,
    };

    const query: TPageRequest = {
      filters: buildSearchFilters(combinedSearchData),
      pagination: {
        page: 1,
        pageSize: 1000,
      },
    };

    const result = await requestWithToken({
      url: apiConfig.search,
      method: "GET",
      data: query,
    });

    if (result.code === 200 || result.success) {
      return result.data || [];
    }
    throw new Error(result?.error || result.message);
  };

  // 使用React Query获取数据
  const actualQueryKey = [queryKey || 'D8dChartData', apiConfig.search, type];
  const { data: chartData, isLoading, error } = useQuery({
    queryKey: actualQueryKey,
    queryFn: fetchChartData,
    enabled: !propsData && !!apiConfig.search,
    retry: 1,
    staleTime: 1000 * 60 * 5 // 5分钟的数据新鲜时间
  });

  // 使用props传入的数据或API获取的数据
  const data = propsData || chartData || [];

  // 处理搜索
  const handleSearch = (values: any) => {
    setManualSearchValues(values);
    queryClient.invalidateQueries({ queryKey: actualQueryKey });
  };

  // 渲染搜索表单
  const renderSearchForm = () => {
    if (!showSearch || !searchFormFieldConfig) return null;
    
    return (
      <Card type="inner" style={{ marginBottom: '16px' }}>
        <SearchForm
          ref={searchFormRef}
          formFieldConfig={searchFormFieldConfig}
          onSearch={handleSearch}
        />
      </Card>
    );
  };

  // 根据图表类型渲染不同的图表
  const renderChart = () => {
    if (isLoading) {
      return <div className="text-center py-6">加载中...</div>;
    }

    if (error) {
      return <div className="text-center py-6 text-red-500">加载失败: {(error as Error).message}</div>;
    }

    if (!data.length) {
      return <div className="text-center py-6">暂无数据</div>;
    }

    const commonConfig = {
      data,
      autoFit: true,
      interaction: { tooltip: true },
    };

    const chartComponents = {
      pie: (
        <Pie
          {...commonConfig}
          angleField={yField}
          colorField={colorField}
          radius={0.8}
          label={{
            position: 'outside',
            text: (item: any) => {
              return `${item[colorField]}\n(${item[yField]})`;
            },
            style: {
              fontSize: 12,
              fontWeight: 500,
            },
          }}
          theme={{
            colors10: ['#36cfc9', '#ff4d4f', '#ffa940', '#73d13d', '#4096ff'],
          }}
        />
      ),
      column: (
        <Column
          {...commonConfig}
          xField={xField}
          yField={yField}
          color="#36cfc9"
          label={{
            position: 'top',
            text: (item: any) => {
              return `${item[yField]}`;
            },
          }}
        />
      ),
      line: (
        <Line
          {...commonConfig}
          xField={xField}
          yField={yField}
          smooth={true}
          color="#36cfc9"
          point={{
            size: 5,
            shape: 'circle',
          }}
          label={{
            position: 'top',
            // style: {
            //   fill: '#fff',
            // },
            text: (items) => {
              console.log("items",items)
              // let content = items[xField];
              // content += `\n(${(items[yField])})`;
              const content = ` ${items[yField]}`;
              return content;
            },
          }}
          autoFit={true}
          interaction={{
            tooltip:false
          }}
        />
      ),
      donut: (
        <Pie
          {...commonConfig}
          angleField={yField}
          colorField={colorField}
          radius={0.9}
          innerRadius={0.8}
          label={{
            position: 'outside',
            text: (item: any) => {
              return `${item[colorField]}\n(${item[yField]})`;
            },
            style: {
              fontSize: 12,
              fontWeight: 500,
            },
          }}
          theme={{
            colors10: ['#36cfc9', '#ff4d4f', '#ffa940', '#73d13d', '#4096ff'],
          }}
        />
      ),
    };

    return chartComponents[type] || null;
  };

  return (
    <div className="w-full">
      {renderSearchForm()}
      <Card title={title}>
        <div style={{ height: 300 }}>
          {renderChart()}
        </div>
      </Card>
    </div>
  );
} 